package com.mcb_wxc.util;

import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;


public class IPUtil {
	
	public static String getRemoteIp(HttpServletRequest request){
		String remoteIp = "";
		
		try{
				
			remoteIp = request.getHeader("x-forwarded-for");
			if(remoteIp != null && !remoteIp.isEmpty()){
				Logger.getLogger(IPUtil.class).info("x-forwarded-for : " + remoteIp);
				Logger.getLogger(IPUtil.class).info("X-Real-IP : " + remoteIp);
				Logger.getLogger(IPUtil.class).info("Proxy-Client-IP : " + remoteIp);
				Logger.getLogger(IPUtil.class).info("WL-Proxy-Client-IP : " + remoteIp);
				Logger.getLogger(IPUtil.class).info("HTTP_CLIENT_IP : " + remoteIp);
				Logger.getLogger(IPUtil.class).info("HTTP_X_FORWARDED_FOR : " + remoteIp);
				Logger.getLogger(IPUtil.class).info("request.getRemoteAddr : " + remoteIp);
				Logger.getLogger(IPUtil.class).info("request.getRemoteHost : " + remoteIp);
			}
				
			if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
				remoteIp = request.getHeader("X-Real-IP");
				Logger.getLogger(IPUtil.class).info("X-Real-IP : " + remoteIp);
			}
				
			if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
				remoteIp= request.getHeader("Proxy-Client-IP");
				Logger.getLogger(IPUtil.class).info("Proxy-Client-IP : " + remoteIp);
			}
				
			if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
				remoteIp= request.getHeader("WL-Proxy-Client-IP");
				Logger.getLogger(IPUtil.class).info("WL-Proxy-Client-IP : " + remoteIp);
			}
			
			if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
				remoteIp= request.getHeader("HTTP_CLIENT_IP");
				Logger.getLogger(IPUtil.class).info("HTTP_CLIENT_IP : " + remoteIp);
			}
				
			if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
				remoteIp= request.getHeader("HTTP_X_FORWARDED_FOR");
				Logger.getLogger(IPUtil.class).info("HTTP_X_FORWARDED_FOR : " + remoteIp);
			}
			
			if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			    remoteIp= request.getRemoteAddr();
			    Logger.getLogger(IPUtil.class).info("request.getRemoteAddr : " + remoteIp);
			}
			
			if (remoteIp == null || remoteIp.isEmpty() || "unknown".equalsIgnoreCase(remoteIp)) {
			    remoteIp= request.getRemoteHost();
			    Logger.getLogger(IPUtil.class).info("request.getRemoteHost : " + remoteIp);
			}
		        
		}catch (Exception e) {
			remoteIp = "";
			Logger.getLogger(IPUtil.class).error("ip : ", e);
		}
		
		
		int indexOf = remoteIp.indexOf(",");
		if(indexOf > 0) {
			remoteIp = remoteIp.substring(0, indexOf);
		}
		
		return remoteIp;
	}
}
